<!---
  首页
--->
<template>
  <div class="app-wrapper" id="app-wrapper" :class="{ Mobile: isMobile }">
    <div class="main-container">
      <div class="sidebar-wrapper">
        <sidebar
          :isMobile="isMobile"
          class="sidebar-container"
          :detail="false"
          :lightHeight="0"
        ></sidebar>
      </div>
      <div
        class="main-layout"
        id="main-layout"
        :style="{
          left: isMobile ? '0' : '50px',
          padding: isMobile ? '1px' : '20px 40px 20px 20px',
          top: isMobile ? '50px' : '0',
          'overflow-y': isMobile ? 'scroll' : isScroll ? 'scroll' : '',
        }"
      >
        <div class="ub_cate_set_container">
          <header class="header clearfix" style="margin-bottom: 2px">
            <div class="title">&nbsp;&nbsp;总体经营情况</div>
          </header>
          <header
            class="sub-header clearfix"
            :style="{
              display: isMobile ? 'block' : 'flex',
              'overflow-y': isMobile ? 'hidden' : 'scroll',
            }"
          >
            <div
              class="item"
              :style="{
                flex: isMobile ? '' : 1,
                width: isMobile ? '50%' : '',
                float: isMobile ? 'left' : '',
                margin: isMobile
                  ? index === 0 || index === 1
                    ? '10px 0 0 0'
                    : '0px 0 0 0'
                  : '16px 20px 0',
              }"
              v-for="(item, index) in subHeader"
              :key="'pop' + index"
            >
              <div class="name">{{ item.name }}</div>
              <div class="value">
                {{ item.value | filterMoney }}
              </div>
            </div>
          </header>
          <div
            class="main-body"
            :style="{
              display:
                !isMobile && isScroll ? 'block' : isMobile ? 'block' : 'flex',
              height: isMobile ? 'auto' : !isMobile && isScroll ? 'auto' : '',
            }"
          >
            <div
              class="charts"
              :style="{
                display: !isMobile && isScroll ? 'block' : '',
                flex: isMobile ? '' : !isMobile && !isScroll ? '1' : '',
                height: isMobile
                  ? '440px'
                  : !isMobile && isScroll
                  ? '400px'
                  : '',
              }"
            >
              <div class="chart-item">
                <chart-header key="1" :title="'现金流'"></chart-header>
                <div class="legend">
                  <div
                    class="item"
                    @click="selectItem(item)"
                    v-for="(item, index) in legend.filter((item, index) => {
                      return index <= 4;
                    })"
                    :key="index"
                  >
                    <div class="color" :style="initStyle(item)"></div>
                    <div class="text" :class="{ 'un-active': !item.active }">
                      {{ item.name }}
                    </div>
                  </div>
                </div>
                <div class="legend2">
                  <div
                    class="item"
                    @click="selectItem(item)"
                    v-for="(item, index) in legend.filter((item, index) => {
                      return index > 4;
                    })"
                    :key="index"
                  >
                    <div class="color" :style="initStyle(item)"></div>
                    <div class="text" :class="{ 'un-active': !item.active }">
                      {{ item.name }}
                    </div>
                  </div>
                </div>
                <pay-chart
                  class="pay-chart-index"
                  :barSelectList="barSelectList"
                  :legend="legend"
                  ref="readerChart"
                  :title="'年度收支'"
                  :chartOption="payChartOption"
                  :renderBindId="'chart-1'"
                  @rePainting="rePainting"
                ></pay-chart>
              </div>
            </div>
            <div
              class="projects"
              id="project"
              :style="{
                height: isMobile
                  ? '520px'
                  : !isMobile && isScroll
                  ? '600px'
                  : '',
                display: !isMobile && isScroll ? 'block' : '',
                width:
                  !isMobile && !isScroll
                    ? '400px'
                    : isMobile && isScroll
                    ? '100%'
                    : '',
                'margin-left': isMobile
                  ? '0'
                  : !isMobile && isScroll
                  ? '0'
                  : '10px',
                'margin-top': isMobile
                  ? '10px'
                  : !isMobile && isScroll
                  ? '10px'
                  : '0',
              }"
            >
              <header class="header clearfix">
                <div
                  class="title"
                  :style="{ 'margin-left': isMobile ? '8px' : '30px' }"
                >
                  项目概况
                </div>
              </header>
              <div class="time">
                {{ getDay() }}
              </div>
              <div class="start-working">
                <div class="left-work">
                  <div class="text">距离<br />完工</div>
                  <div class="icon"></div>
                  <div class="times">{{ projectInfo["距离完工"] }}&nbsp;天</div>
                </div>
                <div class="right-work">
                  <div class="start">
                    <div class="left">开工：</div>
                    <div class="right">
                      <div class="plan">
                        基准计划：{{ projectInfo["基准开工"] }}
                      </div>
                      <div class="real">
                        实际开始：{{ projectInfo["实际开工"] }}
                      </div>
                    </div>
                  </div>
                  <div class="end">
                    <div class="left">完工：</div>
                    <div class="right">
                      <div class="plan">
                        基准计划：{{ projectInfo["基准完工"] }}
                      </div>
                      <div class="real">
                        当前预计：{{ projectInfo["预计完工"] }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- :style="{ height: isMobile ? '' : chartHeight * 2 - 60 + 'px' }" -->
              <div class="project-table">
                <div class="status">
                  <div class="item">
                    <div class="color plan"></div>
                    <div class="text">计划</div>
                  </div>
                  <div class="item">
                    <div class="color real"></div>
                    <div class="text">实际</div>
                  </div>
                </div>
                <div id="gauge"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  homeProjectOverview,
  homeProjectReport,
  homeTableData
} from '@/api/api'
import res from './a.js'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { isMobile } from '@/utils/index'
import PayChart from '@/components/pay_chart.vue'
import ChartHeader from '@/components/chart_header.vue'
import Sidebar from '@/components/Sidebar.vue'
import { IndexJson } from '@/json/index'
import { Legend } from '@/json/cashflow'
export default {
  name: 'Index',
  components: {
    ChartHeader,
    Sidebar,
    PayChart
  },
  data () {
    return {
      legend: Legend,
      dataList: [],
      myChart: null,
      topShow: false,
      bottomShow: false,
      chartShow: true,
      chartShow1: true,
      projectInfo: {
        距离完工: '0',
        AC: '0',
        CPI: '0',
        PV: '0',
        SPI: '0',
        startBase: '',
        startActual: '',
        endBase: '',
        startCurrent: ''
      },
      isScroll: false,
      barList: [],
      barSelectList: IndexJson.barSelectList, // 折线图下拉选数据
      lineSelectList: [], // 柱状图 下拉选数据
      subHeader: [
        {
          name: '年度应收',
          value: '0'
        },
        {
          name: '年度实收',
          value: '0'
        },
        {
          name: '年度实付',
          value: '0'
        },
        {
          name: '累计应收',
          value: '0'
        },
        {
          name: '累计实收',
          value: '0'
        },
        {
          name: '累计实付',
          value: '0'
        }
      ], // 总体经营情况数据 总体经营情况 数据
      areaList: [], // 区域列表数据
      chartHeight: 300, // 图表高度
      isMobile: false,
      payChartOption: {}
    }
  },
  filters: {
    filterMoney: (money) => {
      return `¥ ${parseInt(money / 10000) || 0}万元`
    }
  },
  computed: {
    getStyle: function () {
      const width = $('#project').width() + 'px'
      return {
        height: width,
        width: width
      }
    }
  },

  methods: {
    rePainting: function (list) {
      const tagList = {
        月度: [0, 1, 2, 3],
        累计: [4, 5, 6, 7],
        现金流: [8, 9]
      }
      if (list.length === 4) {
        for (let i = 0; i <= 9; i++) {
          this.payChartOption.series[i].data = this.dataList[i]
        }
        this.legend.forEach((v) => {
          v.active = true
        })
      } else {
        const str = JSON.stringify(list)
        for (let i = 0; i <= 9; i++) {
          this.payChartOption.series[i].data = []
          this.legend[i].active = false
        }
        if (str.includes('月度')) {
          tagList['月度'].forEach((item) => {
            this.payChartOption.series[item].data = this.dataList[item]
            this.legend[item].active = true
          })
        }
        if (str.includes('累计')) {
          tagList['累计'].forEach((item) => {
            this.payChartOption.series[item].data = this.dataList[item]
            this.legend[item].active = true
          })
        }
        if (str.includes('现金流')) {
          tagList['现金流'].forEach((item) => {
            this.payChartOption.series[item].data = this.dataList[item]
            this.legend[item].active = true
          })
        }
      }
      this.$EventBus.$emit('rePainting')
    },
    selectItem: function (item) {
      if (item.active) {
        this.payChartOption.series[item.key].data = []
      } else {
        this.payChartOption.series[item.key].data = this.dataList[item.key]
      }
      item.active = !item.active
      setTimeout(() => {
        this.$EventBus.$emit('rePainting')
        this.$EventBus.$emit('asyncSelect', item, this.legend)
      }, 100)
    },
    initStyle: function (item) {
      const style = {}
      if (item.type === 1) {
        style.background = item.bg
        style.width = '10px'
        style.height = '10px'
        style['border-radius'] = '2px'
      } else if (item.type === 2) {
        style.width = '16px'
        style.height = '4px'
        style.background = item.bg
      } else {
        style.width = '16px'
        style.height = '1px'
        style['border-top'] = `1px dashed ${item.bg}`
      }
      return style
    },
    getDay: function () {
      return `今天： ${dayjs().format('YYYY年MM月DD日')}`
    },

    /**
     * 获取 总体经营情况数据
     */
    getHeaderData: async function () {
      // 预置数据结构
      const response = await homeProjectReport(this.$route.query.projectId)
      if (response) {
        for (const key in response) {
          if (response.hasOwnProperty(key)) {
            if (key === 'yearReceivable') {
              // 年度应收 / 年度新签合同
              this.subHeader[0].value = response[key]
            } else if (key === 'yearCoCost') {
              // 年度实收 / 年度生效合同
              this.subHeader[1].value = response[key]
            } else if (key === 'yearPay') {
              // 年度实付 / 年度项目产值
              this.subHeader[2].value = response[key]
            } else if (key === 'totalReceivable') {
              // 累计应收 / 年度项目收款
              this.subHeader[3].value = response[key]
            } else if (key === 'totalReceipt') {
              // 累计实收 / 年度项目付款
              this.subHeader[4].value = response[key]
            } else if (key === 'totalPay') {
              // 累计实付 / 年度项目效益
              this.subHeader[5].value = response[key]
            }
          }
        }
      }
      this.$forceUpdate()
    },

    // 项目情况
    getHomeProjectOverview: async function () {
      const response = await homeProjectOverview(this.$route.query.projectId)
      if (response) {
        for (const key in response) {
          if (Object.hasOwnProperty.call(response, key)) {
            this.projectInfo[key] = response[key]
          }
        }
        this.renderAgue()
      }
    },

    /**
     * 现金流
     */
    getAmountsData: async function () {
      var response = await homeTableData(this.$route.query.projectId)
      const yearMap = {}
      const monthMap = {}
      for (const key in response) {
        if (Object.hasOwnProperty.call(response, key)) {
          const item = response[key] || []
          if (item.length) {
            item.forEach((v) => {
              const year = dayjs(v.key).format('YYYY')
              const yearMonth = dayjs(v.key).format('YYYYMM')
              yearMap[year] = year
              monthMap[yearMonth] = yearMonth
            })
          }
        }
      }
      const keys = Object.keys(yearMap)
      const startM = dayjs(Object.keys(monthMap)[0]).format('M')
      const endM = dayjs(
        Object.keys(monthMap)[Object.keys(monthMap).length - 1]
      ).format('M')
      for (const key in response) {
        if (Object.hasOwnProperty.call(response, key)) {
          const item = response[key] || []
          const yearMonthMap = {}
          if (item.length) {
            item.forEach((v) => {
              const yearMonth = dayjs(v.key).format('YYYY-MM')
              yearMonthMap[yearMonth] = yearMonth
            })
            const itemCopy = JSON.stringify(item)
            for (let i = 0; i < keys.length; i++) {
              const year = keys[i]
              for (
                let j = i === 0 ? startM : 1;
                j <= (i === keys.length - 1 ? endM : 12);
                j++
              ) {
                const month = j < 10 ? `0${j}` : j
                if (!itemCopy.includes(`${year}-${month}`)) {
                  item.push({
                    key: `${year}-${month}`,
                    value: null
                  })
                }
              }
            }
            const ks = Object.keys(yearMonthMap)
            const maxYM = ks[ks.length - 1]
            item.sort((a, b) => a.key.localeCompare(b.key))
            if (!key.includes('month')) {
              for (let i = 0; i < item.length; i++) {
                const element = item[i]
                if (
                  i > 0 &&
                  !element.value &&
                  dayjs(element.key).format('YYYYMM') <=
                    dayjs(maxYM).format('YYYYMM')
                ) {
                  element.value = item[i - 1].value
                }
              }
            }
          }
        }
      }
      // 计划付款（月度）
      const plannedRevenueBar = response['planCollection(month)'] || [] // ['计划付款（月度）'] || []// response['计划收入']
      const plannedRevenueBarData = []
      plannedRevenueBar.forEach((v) => {
        if (v.value != null) {
          plannedRevenueBarData.push((v.value / 100000000).toFixed(2))
        } else {
          plannedRevenueBarData.push(null)
        }
      })
      // 实际收款（月度）
      var realIncomeBar = response['actualCollection(month)'] || [] // ['实际收款（月度）'] || [] // response['实际收入']
      const realIncomeBarData = []
      realIncomeBar.forEach((v) => {
        realIncomeBarData.push(v.value != null ? (v.value / 100000000).toFixed(2) : null)
      })

      // 计划付款（月度）
      const targetCostBar = response['planPay(month)'] || [] // ['计划付款（月度）'] || [] // response['目标成本']
      const targetCostBarData = []
      targetCostBar.forEach((v) => {
        targetCostBarData.push(v.value != null ? -(v.value / 100000000).toFixed(2) : null)
      })

      // 实际付款（月度）
      const actualCostBar = response['actualPay(month)'] || [] // ['实际付款（月度）'] || [] // response['实际支出']
      const actualCostBarData = []
      actualCostBar.forEach((v) => {
        actualCostBarData.push(v.value != null ? -(v.value / 100000000).toFixed(2) : null)
      })

      // 累计计划收款
      const accumulatedPlannedRevenueLine = response['planCollection'] // ['累计计划收款'] || [] // response['累计计划收入'] || []
      let lastValueAccumulatedPlannedRevenue = 0
      let lastValueAccumulatedPlannedRevenueIndex = 0
      var accumulatedPlannedRevenueLineLen =
        accumulatedPlannedRevenueLine.length
      for (
        let index = accumulatedPlannedRevenueLineLen - 1;
        index > 0;
        index--
      ) {
        if (
          !accumulatedPlannedRevenueLine[index].value &&
          accumulatedPlannedRevenueLine[index - 1].value
        ) {
          lastValueAccumulatedPlannedRevenueIndex = index
          lastValueAccumulatedPlannedRevenue =
            accumulatedPlannedRevenueLine[index - 1].value
          break
        }
      }

      for (
        let index = 0;
        index < accumulatedPlannedRevenueLineLen;
        index++
      ) {
        if (index >= lastValueAccumulatedPlannedRevenueIndex && lastValueAccumulatedPlannedRevenueIndex > 0) {
          accumulatedPlannedRevenueLine[index].value =
            lastValueAccumulatedPlannedRevenue
        }
      }
      const accumulatedPlannedRevenueLineData = []
      accumulatedPlannedRevenueLine.forEach((v) => {
        if (v.value !== null) {
          accumulatedPlannedRevenueLineData.push(
            (v.value / 100000000).toFixed(2)
          )
        } else {
          accumulatedPlannedRevenueLineData.push(null
          )
        }
      })
      // 累计计划付款
      const cumulativetargetCostLine = response['planPay'] || [] // ['累计计划付款'] || []// response['累计目标成本'] || []
      const cumulativetargetCostLineData = []

      let lastValueCumulativetargetCost = 0
      let lastValueCumulativetargetCostIndex = 0
      var cumulativetargetCostLineLen = cumulativetargetCostLine.length
      for (let index = cumulativetargetCostLineLen - 1; index > 0; index--) {
        if (
          !cumulativetargetCostLine[index].value &&
          cumulativetargetCostLine[index - 1].value
        ) {
          lastValueCumulativetargetCostIndex = index
          lastValueCumulativetargetCost =
            cumulativetargetCostLine[index - 1].value
          break
        }
      }

      for (
        let index = 0;
        index < cumulativetargetCostLineLen;
        index++
      ) {
        if (index >= lastValueCumulativetargetCostIndex && lastValueCumulativetargetCostIndex > 0) {
          cumulativetargetCostLine[index].value =
            lastValueCumulativetargetCost
        }
      }

      cumulativetargetCostLine.forEach((v) => {
        debugger
        if (v.value !== null) {
          cumulativetargetCostLineData.push((v.value / 100000000).toFixed(2))
        } else {
          cumulativetargetCostLineData.push(null
          )
        }
      })

      // 累计实际收款
      const ccumulatedActualIncomeLine = response['actualCollection'] || [] // ['累计实际收款'] || [] // response['累计实际收入'] || []

      // let lastValueActualCollection = 0
      // let lastValueActualCollectionIndex = 0
      // var cccumulatedActualIncomeLen = ccumulatedActualIncomeLine.length
      // for (let index = cccumulatedActualIncomeLen - 1; index > 0; index--) {
      //   if (
      //     !ccumulatedActualIncomeLine[index].value &&
      //     ccumulatedActualIncomeLine[index - 1].value
      //   ) {
      //     lastValueActualCollectionIndex = index
      //     lastValueActualCollection =
      //       ccumulatedActualIncomeLine[index - 1].value
      //     break
      //   }
      // }

      // for (let index = cccumulatedActualIncomeLen - 1; index > 0; index--) {
      //   if (
      //     !ccumulatedActualIncomeLine[index].value &&
      //     index >= lastValueActualCollectionIndex
      //   ) {
      //     ccumulatedActualIncomeLine[index].value = lastValueActualCollection
      //   }
      // }

      const ccumulatedActualIncomeLineData = []
      ccumulatedActualIncomeLine.forEach((v) => {
        if (v.value !== null) {
          ccumulatedActualIncomeLineData.push((v.value / 100000000).toFixed(2))
        } else {
          ccumulatedActualIncomeLineData.push(null)
        }
      })
      // 累计实际付款
      const cumulativeForecastRevenueLine = response['actualPay'] || [] // ['累计实际付款'] || [] // response['累计预测收入'] || []
      // let lastValueActualPay = 0
      // let lastValueActualPayIndex = 0
      // var cumulativeForecastRevenueLineLen =
      //   cumulativeForecastRevenueLine.length
      // for (
      //   let index = cumulativeForecastRevenueLineLen - 1;
      //   index > 0;
      //   index--
      // ) {
      //   if (
      //     !cumulativeForecastRevenueLine[index].value &&
      //     cumulativeForecastRevenueLine[index - 1].value
      //   ) {
      //     lastValueActualPayIndex = index
      //     lastValueActualPay = cumulativeForecastRevenueLine[index - 1].value
      //     break
      //   }
      // }

      // for (
      //   let index = cumulativeForecastRevenueLineLen - 1;
      //   index > 0;
      //   index--
      // ) {
      //   if (
      //     !cumulativeForecastRevenueLine[index].value &&
      //     index >= lastValueActualPayIndex
      //   ) {
      //     cumulativeForecastRevenueLine[index].value = lastValueActualPay
      //   }
      // }

      const cumulativeForecastRevenueLineData = []
      cumulativeForecastRevenueLine.forEach((v) => {
        if (v.value !== null) {
          cumulativeForecastRevenueLineData.push(
            (v.value / 100000000).toFixed(2)
          )
        } else {
          cumulativeForecastRevenueLineData.push(null)
        }
      })
      // 累计净现金流
      const accumulatedActualCostLine = response['netCashFlow'] || [] // ['累计净现金流'] || [] // response['累计实际支出'] || []
      // let lastValueNetCashFlow = 0;
      // let lastValueNetCashFlowIndex = 0;
      // var accumulatedActualCostLineLen = accumulatedActualCostLine.length;
      // for (let index = accumulatedActualCostLineLen - 1; index > 0; index--) {
      //   if (
      //     !accumulatedActualCostLine[index].value &&
      //     accumulatedActualCostLine[index - 1].value
      //   ) {
      //     lastValueNetCashFlowIndex = index;
      //     lastValueNetCashFlow = accumulatedActualCostLine[index - 1].value;
      //     break;
      //   }
      // }

      // for (let index = accumulatedActualCostLineLen - 1; index > 0; index--) {
      //   if (
      //     !accumulatedActualCostLine[index].value &&
      //     index >= lastValueNetCashFlowIndex
      //   ) {
      //     accumulatedActualCostLine[index].value = lastValueNetCashFlow;
      //   }
      // }
      const accumulatedActualCostLineData = []
      accumulatedActualCostLine.forEach((v) => {
        if (v.value !== null) {
          accumulatedActualCostLineData.push((v.value / 100000000).toFixed(2))
        } else {
          accumulatedActualCostLineData.push(null)
        }
      })

      // 预测现金流
      let cumulativeForecastCostLine = response['forecastCashFlow'] || [] /// ['预测现金流'] || []
      debugger
      // let lastValueForecastCashFlow = 0
      // let lastValueForecastCashFlowIndex = 0
      // var cumulativeForecastCostLineLen = cumulativeForecastCostLine.length
      // for (let index = cumulativeForecastCostLineLen - 1; index > 0; index--) {
      //   if (
      //     !cumulativeForecastCostLine[index].value &&
      //     cumulativeForecastCostLine[index - 1].value
      //   ) {
      //     lastValueForecastCashFlowIndex = index
      //     lastValueForecastCashFlow =
      //       cumulativeForecastCostLine[index - 1].value
      //     break
      //   }
      // }

      // for (let index = cumulativeForecastCostLineLen - 1; index > 0; index--) {
      //   if (
      //     !cumulativeForecastCostLine[index].value &&
      //     index >= lastValueForecastCashFlowIndex
      //   ) {
      //     cumulativeForecastCostLine[index].value = lastValueForecastCashFlow;
      //   }
      // }
      // cumulativeForecastCostLine = cumulativeForecastCostLine.slice(0, lastValueForecastCashFlowIndex)
      const cumulativeForecastCostLineData = []
      cumulativeForecastCostLine.forEach((v) => {
        if (v.value != null) {
          cumulativeForecastCostLineData.push((v.value / 100000000).toFixed(2))
        } else {
          cumulativeForecastCostLineData.push(null)
        }
      })

      this.payChartOption.series[0].data = [...[], ...plannedRevenueBarData]
      this.dataList[0] = [...[], ...plannedRevenueBarData]

      this.payChartOption.series[1].data = [...[], ...realIncomeBarData]
      this.dataList[1] = [...[], ...realIncomeBarData]

      this.payChartOption.series[2].data = [...[], ...targetCostBarData]
      this.dataList[2] = [...[], ...targetCostBarData]

      this.payChartOption.series[3].data = [...[], ...actualCostBarData]
      this.dataList[3] = [...[], ...actualCostBarData]

      this.payChartOption.series[4].data = [
        ...[],
        ...accumulatedPlannedRevenueLineData
      ]
      this.dataList[4] = [...[], ...accumulatedPlannedRevenueLineData]

      this.payChartOption.series[5].data = [
        ...[],
        ...cumulativetargetCostLineData
      ]
      this.dataList[5] = [...[], ...cumulativetargetCostLineData]

      this.payChartOption.series[6].data = [
        ...[],
        ...ccumulatedActualIncomeLineData
      ]
      this.dataList[6] = [...[], ...ccumulatedActualIncomeLineData]

      this.payChartOption.series[7].data = [
        ...[],
        ...cumulativeForecastRevenueLineData
      ]
      this.dataList[7] = [...[], ...cumulativeForecastRevenueLineData]

      this.payChartOption.series[8].data = [
        ...[],
        ...accumulatedActualCostLineData
      ]
      this.dataList[8] = [...[], ...accumulatedActualCostLineData]
      this.payChartOption.series[9].data = [
        ...[],
        ...cumulativeForecastCostLineData
      ]
      this.dataList[9] = [...[], ...cumulativeForecastCostLineData]

      let Y1Max = 0
      const allBarArr = [
        ...plannedRevenueBarData,
        ...realIncomeBarData,
        ...targetCostBarData,
        ...actualCostBarData,
        ...accumulatedActualCostLineData,
        ...cumulativeForecastCostLineData
      ]
      for (let i = 0; i < allBarArr.length; i++) {
        const item = allBarArr[i]
        if (item && Math.abs(Number(item)) > Math.abs(Number(Y1Max))) {
          Y1Max = Math.abs(Number(item))
        }
      }
      if (!Y1Max) {
        Y1Max = 1.0
      }
      Y1Max = Math.abs(Y1Max)
      const Y1AddSpce = Number(Y1Max) / 5
      Y1Max = Number(Y1Max) + Y1AddSpce // y轴上下留白
      if (Y1Max % 1 !== 0) {
        console.log(Y1Max)
        if (Y1Max < 0.1) {
          Y1Max = Y1Max.toFixed(2)
        } else if (Y1Max < 1) {
          Y1Max = Y1Max.toFixed(1)
        } else {
          Y1Max = Y1Max.toFixed(0)
        }
      }
      this.payChartOption.yAxis[0].min = -Y1Max
      this.payChartOption.yAxis[0].max = Y1Max
      this.payChartOption.yAxis[0].interval = Y1Max / 5
      let Y2Max = 0
      const allLineArr = [
        ...accumulatedPlannedRevenueLineData,
        ...cumulativetargetCostLineData,
        ...ccumulatedActualIncomeLineData,
        ...cumulativeForecastRevenueLineData,
        ...accumulatedActualCostLineData,
        ...cumulativeForecastCostLineData
      ]
      for (let i = 0; i < allLineArr.length; i++) {
        const item = allLineArr[i]
        if (item && Math.abs(Number(item)) > Y2Max) {
          Y2Max = item
        }
      }
      if (!Y2Max) {
        Y2Max = 1
      }
      const Y2AddSpce = Number(Y2Max) / 5
      Y2Max = Number(Y2Max) + Y2AddSpce // y轴上下留白
      if (Y2Max % 1 !== 0) {
        Y2Max = Y2Max.toFixed(2)
      }
      this.payChartOption.yAxis[1].max = Y2Max
      this.payChartOption.yAxis[1].interval = Y2Max / 5
      const X2 = []
      const X0 = []
      const X1 = []
      for (let index = 0; index < keys.length; index++) {
        X2.push({
          value: keys[index],
          textStyle: {
            height: 90,
            fontSize: 14,
            lineHeight: 90,
            color: '#fff'
          }
        })
        for (
          let j = index === 0 ? startM : 1;
          j <= (index === keys.length - 1 ? endM : 12);
          j++
        ) {
          X1.push({
            value: j,
            textStyle: {
              height: 50,
              fontSize: 13,
              lineHeight: 50,
              color: '#fff'
            }
          })
          X0.push(`M${j}`)
        }
      }
      this.payChartOption.xAxis[0].data = X0
      this.payChartOption.xAxis[1].data = X1
      this.payChartOption.xAxis[2].data = X2
      setTimeout(() => {
        this.$EventBus.$emit('rePainting')
      }, 100)
    },

    renderAgue: function () {
      if (this.myChart) {
        this.myChart.dispose()
      }
      if (document.getElementById('gauge')) {
        const flag = $('#project').height() < 450
        var option = {
          series: [
            // 中圈
            {
              name: '转速',
              type: 'gauge',
              center: ['50%', '50%'], // 默认全局居中
              radius: flag ? '40%' : this.isMobile ? '40%' : '50%',
              splitNumber: 4,
              axisLine: {
                // 坐标轴线
                lineStyle: {
                  // 属性lineStyle控制线条样式
                  color: [[1, '#fff']],
                  width: 1,
                  shadowBlur: 10
                }
              },
              axisLabel: {
                // 刻度
                show: false
              },
              axisTick: {
                // 坐标轴小标记
                show: false
              },
              splitLine: {
                // 分隔线
                show: false
              },
              pointer: {
                show: false
              },
              detail: {
                show: true,
                width: 40,
                height: 14,
                fontSize: flag ? 10 : this.isMobile ? 10 : 16,
                color: '#fff',
                formatter: `SPI ${this.projectInfo.SPI}`,
                offsetCenter: flag
                  ? ['150%', '203%']
                  : this.isMobile
                    ? ['80%', '203%']
                    : ['60%', '162%']
              },
              data: [
                {
                  value: 100
                }
              ]
            },
            {
              name: '转速',
              type: 'gauge',
              center: ['50%', '50%'], // 默认全局居中
              radius: flag ? '40%' : this.isMobile ? '40%' : '50%',
              splitNumber: 4,
              axisLine: {
                // 坐标轴线
                lineStyle: {
                  // 属性lineStyle控制线条样式
                  color: [[1, '#fff']],
                  width: 1,
                  shadowBlur: 10
                }
              },
              axisLabel: {
                // 刻度
                show: false
              },
              axisTick: {
                // 坐标轴小标记
                show: false
              },
              splitLine: {
                // 分隔线
                show: false
              },
              pointer: {
                show: false
              },
              detail: {
                show: true,
                width: 40,
                height: 14,
                fontSize: flag ? 10 : this.isMobile ? 10 : 16,
                color: '#fff',
                formatter: `CPI ${this.projectInfo.CPI}`,
                offsetCenter: flag
                  ? ['150%', '203%']
                  : this.isMobile
                    ? ['190%', '203%']
                    : ['150%', '162%']
              },
              data: [
                {
                  value: 100
                }
              ]
            },
            // 实际
            {
              type: 'gauge',
              center: ['50%', '50%'], // 默认全局居中
              radius: '90%',
              // min: 0,
              // max: 100,
              name: '实际',
              axisLine: {
                // 坐标轴线
                lineStyle: {
                  color: [[1, '#fff']], // 属性lineStyle控制线条样式
                  width: 0
                }
              },
              itemStyle: {
                normal: {
                  color: '#FF0000'
                }
              },
              axisTick: {
                length: 3
              },
              axisLabel: {
                // 坐标轴小标记
                show: false,
                textStyle: {
                  // 属性lineStyle控制线条样式
                  fontWeight: 'bolder',
                  fontSize: 10,
                  fontFamily: 'numfont'
                }
              },
              splitLine: {
                // 分隔线
                show: false
              },
              pointer: {
                width: 3,
                length: '90%',
                itemStyle: {
                  color: '#009348'
                }
              },
              detail: {
                width: 40,
                height: 14,
                fontSize: flag ? 10 : this.isMobile ? 10 : 16,
                color: '#fff',
                formatter: 'AC {value}%',
                offsetCenter: ['-20%', '90%']
              },
              data: [
                {
                  value: this.projectInfo.AC
                }
              ]
            },
            // 计划
            {
              type: 'gauge',
              center: ['50%', '50%'], // 默认全局居中
              radius: '90%',
              min: 0,
              max: 100,
              name: '计划',
              axisTick: {
                length: 3
              },
              axisLine: {
                // 坐标轴线
                lineStyle: {
                  color: [[1, '#fff']], // 属性lineStyle控制线条样式
                  width: 1
                }
              },
              pointer: {
                width: 3,
                length: '90%',
                itemStyle: {
                  color: '#0093c8'
                }
              },
              axisLabel: {
                distance: 5,
                textStyle: {
                  fontWeight: 'bolder',
                  fontSize: flag ? 10 : 14,
                  color: '#fff'
                }
              },
              splitLine: {
                // 分隔线
                length: 5, // 属性length控制线长
                lineStyle: {
                  // 属性lineStyle（详见lineStyle）控制线条样式
                  width: 1
                }
              },
              detail: {
                width: 40,
                height: 14,
                fontSize: flag ? 10 : this.isMobile ? 10 : 16,
                color: '#fff',
                formatter: 'PV {value}%',
                offsetCenter: ['-75%', '90%']
              },
              data: [
                {
                  value: this.projectInfo.PV
                }
              ]
            }
          ]
        }
        this.myChart = echarts.init(document.getElementById('gauge'))
        this.myChart.setOption(option)
      }
    },
    windowRizes: function () {
      const chartHeight = ($(window).height() - 40 - 122) / 2 - 2
      this.chartHeight = this.isMobile
        ? chartHeight <= 250
          ? 250
          : chartHeight
        : chartHeight <= 300
          ? 300
          : chartHeight
      this.isScroll = this.isMobile === false && $(window).width() < 992
      this.chartShow = false
      this.chartShow1 = false
      this.renderAgue()
      this.$EventBus.$emit('rePainting')
      this.$forceUpdate()
    },
    initOption: function () {
      this.payChartOption = {
        // 年度收支 数据模型
        tooltip: {
          show: true,
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              show: false
            }
          },
          formatter: function (params) {
            let res = '<ul class="formatter-ul">'
            res += '<div class="title">' + params[0].axisValueLabel + '</div>'
            for (let index = 0; index < params.length; index++) {
              const element = params[index]
              const isUndefined = typeof element.value === 'undefined'
              if (!isUndefined && element.value) {
                let sub = '<li class="formatter-li">'
                let type = ''
                if (element.seriesType === 'bar') {
                  type =
                    "<div class='pre-bar' style='background:" +
                    element.color +
                    "'></div>"
                } else {
                  if (element.seriesId.includes('d')) {
                    type =
                      "<div class='pre-line-dashed'><span style='background:" +
                      element.color +
                      "'></span> <span style='background:" +
                      element.color +
                      "'></span> <span style='background:" +
                      element.color +
                      "'></span> </div>"
                  } else {
                    type =
                      "<div class='pre-line' style='background:" +
                      element.color +
                      "'></div>"
                  }
                }
                const seriesName =
                  "<div class='series-name'>" + element.seriesName + '</div>'
                const value =
                  "<div class='series-value'>" +
                ((element.componentIndex === 8 || element.componentIndex === 9) ? (element.value == 0) ? -(element.value) : element.value : Math.abs(element.value)) +
                  '</div>'
                sub += type
                sub += seriesName
                sub += value
                sub += '</li>'
                res += sub
              } else {
                // res += '<div>无数据</div>'
              }
            }
            return res
          },
          backgroundColor: 'rgba(0, 0, 0, 0.3)',
          padding: 10,
          textStyle: {
            color: '#fff'
          }
        },
        dataZoom: [
          {
            id: 'dataZoomX',
            start: 0, // 默认为0
            end: 100, // 默认为100
            type: 'slider',
            show: false,
            xAxisIndex: [0, 1, 2],
            handleSize: 0, // 滑动条的 左右2个滑动条的大小
            height: 8, // 组件高度
            left: 50, // 左边的距离
            right: 40, // 右边的距离
            bottom: 26, // 右边的距离
            handleColor: '#ddd', // h滑动图标的颜色
            handleStyle: {
              borderColor: '#cacaca',
              borderWidth: '1',
              shadowBlur: 2,
              background: '#ddd',
              shadowColor: '#ddd'
            },
            fillerColor: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              {
                offset: 0,
                color: '#1eb5e5'
              },
              {
                offset: 1,
                color: '#5ccbb1'
              }
            ]),
            backgroundColor: '#ddd', // 两边未选中的滑动条区域的颜色
            showDataShadow: false, // 是否显示数据阴影 默认auto
            showDetail: false, // 即拖拽时候是否显示详细数值信息 默认true
            handleIcon:
              'M-292,322.2c-3.2,0-6.4-0.6-9.3-1.9c-2.9-1.2-5.4-2.9-7.6-5.1s-3.9-4.8-5.1-7.6c-1.3-3-1.9-6.1-1.9-9.3c0-3.2,0.6-6.4,1.9-9.3c1.2-2.9,2.9-5.4,5.1-7.6s4.8-3.9,7.6-5.1c3-1.3,6.1-1.9,9.3-1.9c3.2,0,6.4,0.6,9.3,1.9c2.9,1.2,5.4,2.9,7.6,5.1s3.9,4.8,5.1,7.6c1.3,3,1.9,6.1,1.9,9.3c0,3.2-0.6,6.4-1.9,9.3c-1.2,2.9-2.9,5.4-5.1,7.6s-4.8,3.9-7.6,5.1C-285.6,321.5-288.8,322.2-292,322.2z'
          },
          {
            type: 'inside',
            show: false,
            xAxisIndex: [0, 1, 2],
            start: 0, // 默认为1
            end: 100 // 默认为100
          }
        ],
        grid: {
          left: this.isMobile ? 30 : 60,
          right: this.isMobile ? 40 : 60,
          bottom: 66,
          top: this.isMobile ? 30 : 40
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisLine: {
              onZero: true,
              lineStyle: {
                color: '#fff'
              }
            },
            splitLine: { show: false },
            splitArea: { show: false },
            axisLabel: {
              fontSize: this.isMobile ? 8 : 10,
              color: '#fff'
            },
            axisTick: {
              show: false
            }
          },
          {
            type: 'category',
            data: [],
            position: 'bottom',
            axisPointer: {
              show: false,
              triggerTooltip: false
            },
            axisLabel: {
              lineHeight: 40,
              align: 'center'
            },
            axisLine: { onZero: true, show: false },
            splitLine: { show: false },
            axisTick: { show: false }
          },
          {
            type: 'category',
            data: [],
            position: 'bottom',
            axisPointer: {
              show: false,
              triggerTooltip: false
            },
            axisLabel: {
              lineHeight: 40,
              align: 'center'
            },
            axisLine: { onZero: true, show: false },
            splitLine: { show: false },
            axisTick: { show: false }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '(亿元)',
            min: -1,
            max: 1,
            interval: this.isMobile ? 2 : 1,
            axisTick: {
              show: true,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            axisLabel: {
              formatter: function (value, index) {
                if (value % 1 === 0) {
                  return value
                }
                return value.toFixed(2)
              },
              color: '#fff'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            splitLine: { show: false },
            nameTextStyle: {
              fontSize: this.isMobile ? 8 : 12,
              color: '#fff'
            }
          },
          {
            type: 'value',
            name: '(亿元)',
            max: 1,
            min: 0,
            interval: this.isMobile ? 2 : 1,
            axisTick: {
              show: true,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            axisLabel: {
              formatter: function (value, index) {
                if (value % 1 === 0) {
                  return value
                }
                return value.toFixed(2)
              },
              color: '#fff'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            splitLine: { show: false },
            nameTextStyle: {
              fontSize: this.isMobile ? 8 : 12
            }
          }
        ],
        series: [
          {
            name: '计划收款',
            type: 'bar',
            typeKey: 1,
            id: '计划收款1',
            barWidth: this.isMobile ? 3 : 5,
            data: [],
            stack: 'one',
            itemStyle: {
              opacity: 1,
              color: '#00ce67'
            }
          },
          {
            name: '实际收款',
            type: 'bar',
            id: '实际收款1',
            typeKey: 2,
            barWidth: this.isMobile ? 3 : 5,
            data: [],
            stack: 'two',
            itemStyle: {
              opacity: 1,
              color: '#008cdc'
            }
          },
          {
            name: '计划付款',
            type: 'bar',
            typeKey: 3,
            id: '计划付款1',
            barWidth: this.isMobile ? 3 : 5,
            data: [],
            stack: 'one',
            itemStyle: {
              opacity: 1,
              color: '#99e9ba'
            }
          },
          {
            name: '实际付款',
            type: 'bar',
            typeKey: 4,
            id: '实际付款1',
            barWidth: this.isMobile ? 3 : 5,
            data: [],
            stack: 'two',
            itemStyle: {
              opacity: 1,
              color: '#94cceb'
            }
          },
          {
            name: '累计计划收款',
            type: 'line',
            yAxisIndex: 1,
            lineStyle: {
              width: this.isMobile ? 1 : 2,
              opacity: 1
            },
            data: [],
            smooth: true,
            showSymbol: false,
            typeKey: 1,
            id: '累计计划收款',
            hoverAnimation: false,
            itemStyle: {
              opacity: 1,
              color: 'rgb(0, 206, 103)'
            }
          },
          {
            name: '累计计划付款',
            type: 'line',
            yAxisIndex: 1,
            lineStyle: {
              width: this.isMobile ? 1 : 2,
              opacity: 1
            },
            data: [],
            showSymbol: false,
            hoverAnimation: false,
            typeKey: 2,
            id: '累计计划付款',
            smooth: true,
            itemStyle: {
              opacity: 1,
              color: 'rgb(153, 233, 186)'
            }
          },
          {
            name: '累计实际收款',
            type: 'line',
            yAxisIndex: 1,
            lineStyle: {
              width: this.isMobile ? 1 : 2,
              opacity: 1
            },
            data: [],
            showSymbol: false,
            hoverAnimation: false,
            typeKey: 3,
            id: '累计实际收款',
            smooth: true,
            itemStyle: {
              opacity: 1,
              color: '#008cdc'
            }
          },

          {
            name: '累计实际付款',
            type: 'line',
            yAxisIndex: 1,
            lineStyle: {
              width: this.isMobile ? 1 : 2,
              opacity: 1
            },
            data: [],
            smooth: true,
            showSymbol: false,
            typeKey: 5,
            id: '累计实际付款',
            hoverAnimation: false,
            itemStyle: {
              opacity: 1,
              color: '#94cceb'
            }
          },

          {
            name: '现金流',
            type: 'line',
            yAxisIndex: 0,
            lineStyle: {
              width: this.isMobile ? 1 : 2,
              opacity: 1
            },
            data: [],
            showSymbol: false,
            hoverAnimation: false,
            typeKey: 4,
            id: '现金流1',
            smooth: false,
            itemStyle: {
              opacity: 1,
              color: '#ffd100'
            }
          },

          {
            name: '预测现金流',
            type: 'line',
            yAxisIndex: 0,
            smooth: false,
            lineStyle: {
              width: this.isMobile ? 1 : 2,
              opacity: 1,
              type: 'dashed'
            },
            data: [],
            showSymbol: false,
            hoverAnimation: false,
            typeKey: 6,
            id: 'd预测现金流1',
            itemStyle: {
              opacity: 1,
              color: '#ffd000'
            }
          }
        ]
      }
    }
  },
  created () {
    this.isMobile = isMobile()
  },
  mounted: async function () {
    this.initOption()
    const chartHeight = ($(window).height() - 40 - 122) / 2 - 2
    this.chartHeight = this.isMobile
      ? chartHeight <= 250
        ? 250
        : chartHeight
      : chartHeight <= 300
        ? 300
        : chartHeight
    this.isScroll = !this.isMobile && $(window).width() <= 992
    $(window).resize(() => {
      this.isMobile = isMobile()
      this.isScroll = !this.isMobile && $(window).width() <= 992
      this.windowRizes()
    })
    this.getHeaderData() // 获取 总体经营情况数据
    this.getHomeProjectOverview()
    this.getAmountsData() // 现金流数据
  }
}
</script>
<style lang="scss" scoped>
.ub_cate_set_container {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  padding-top: 8px;
}

.header {
  height: 60px;
  width: 100%;
  color: #ffffff;
  border-bottom: 1px solid #ffffff;
  .title {
    margin-left: 10px;
    margin-top: 20px;
    height: 14px;
    line-height: 14px;
    padding-left: 10px;
    border-left: 4px solid #008bf3;
    font-weight: 700;
    font-size: 17px;
    color: #ffffff;
  }
}

.sub-header {
  width: 100%;
  display: flex;
  min-height: 80px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ffffff;
  .item {
    background: #233a61;
    border: 1px solid #8e8c91;
    min-width: 140px;
    height: 80px;
    .name {
      margin-top: 5px;
      text-align: left;
      color: #fff;
      padding-left: 10px;
      font-size: 16px;
      font-weight: 700;
    }
    .value {
      margin-top: 20px;
      text-align: right;
      padding-right: 10px;
      color: #fff;
      font-size: 14px;
      font-weight: 700;
    }
  }
}

.theader {
  display: flex;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #ffffff;
  .project-name {
    flex: 1;
    color: #aeaeae;
    font-size: 14px;
  }
  .project-process {
    width: 130px;
    color: #aeaeae;
    font-size: 14px;
  }
}

.main-body {
  overflow: hidden;
  margin-top: 10px;
  height: calc(100% - 220px);
  .projects {
    position: relative;
    border: 1px solid #ffffff;
    display: flex;
    flex-direction: column;
    .projects-inner {
      margin-top: 2px;
      overflow: hidden;
    }
  }
}

.table td,
.table th {
  border: none;
}

.table-suspend {
  position: absolute;
  background: #ffff;
  top: 42px;
}
.project-table {
  height: 100%;
  display: flex;
  justify-content: center;
  position: relative;
  padding-top: 40px;
  #gauge {
    width: 100%;
    height: 100%;
  }
  .status {
    position: absolute;
    right: 0px;
    top: 40px;
    width: 80px;
    .item {
      display: flex;
      height: 16px;
      align-items: center;
      margin-bottom: 16px;
      .color {
        height: 16px;
        width: 16px;
        margin-right: 4px;
        border-radius: 2px;
      }
      .text {
        flex: 1;
        font-size: 14px;
        color: #fff;
        font-weight: 700;
      }
      .plan {
        background: #009348;
      }
      .real {
        background: #0093c8;
      }
    }
  }
}

.cash-flow {
  border-bottom: 1px solid #eff0f4;
}
.projects {
  header {
    border: none;
  }
  .time {
    font-size: 16px;
    color: #ffffff;
    font-weight: 700;
    padding: 10px 0px 10px 8px;
    margin-top: 10px;
  }
  .start-working {
    display: flex;
    border-bottom: 1px dashed #ffffff;
    .left-work {
      flex: 3;
      display: flex;
      align-items: center;
      .text {
        font-size: 16px;
        font-weight: 700;
        color: #ffffff;
        padding-left: 8px;
      }
      .icon {
        margin: 0 6px;
        width: 60px;
        height: 60px;
        background: url("./clock.png") center center no-repeat;
        background-size: 100% 100%;
      }
      .times {
        font-size: 16px;
        font-weight: 700;
        color: #ffffff;
      }
    }
    .right-work {
      margin-bottom: 10px;
      flex: 4;
      .start,
      .end {
        display: flex;
        align-items: center;
        .left {
          width: 50px;
          font-size: 16px;
          font-weight: 700;
          color: #fff;
        }
        .right {
          .plan {
            font-size: 15px;
            font-weight: 700;
            color: #009149;
            margin-bottom: 5px;
          }
          .real {
            font-size: 15px;
            font-weight: 700;
            color: #0093c8;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
}
.flag {
  vertical-align: middle;
}
.is-loading {
  .name {
    width: 50%;
    margin: 5px auto !important;
    height: 16px;
  }
  .plan {
    height: 16px;
  }
  .reality {
    height: 16px;
  }
}
.title-loading {
  height: 20px;
  margin-top: 10px;
  width: 60%;
}
.chart-item {
  position: relative;

  height: 100%;
  border: 1px solid #ffffff;
  .chart-box {
    border: 10px solid #ffffff;
  }
}
.pay-chart-index {
  margin-top: 20px;
  height: 80%;
}
.legend,
.legend2 {
  width: 100%;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  overflow: hidden;
  .item {
    cursor: pointer;
    display: flex;
    width: auto;
    height: 30px;
    align-items: center;
    justify-content: center;
    margin: 0 5px;
    .text {
      font-size: 12px;
      margin-left: 4px;
      color: #fff;
      white-space: nowrap;
    }
  }
}
.legend2 {
  margin-top: 0;
  position: absolute;
}
.un-active {
  color: #747474 !important;
}
</style>
